#include "Camera.h"
#include <opencv2/opencv.hpp>
class Camera : public Device {
public:
    explicit Camera(const std::string& config) {
        Json::Value params;
        Json::Reader().parse(config, params);
        resolution = params.get("resolution", "1920x1080").asString();
        frameRate = params.get("frame_rate", 30).asInt();
        initCamera();
    }
    void executeCommand(const std::string& command) override {
        std::lock_guard<std::mutex> lock(deviceMutex);
        Json::Value cmd;
        Json::Reader().parse(command, cmd);
        if (cmd["action"] == "start_recording") {
            recording = true;
            startRecordingThread();
        } else if (cmd["action"] == "stop_recording") {
            recording = false;
        } else if (cmd["action"] == "set_resolution") {
            setResolution(cmd["width"].asInt(), cmd["height"].asInt());
        }
    }
    std::string getStatus() const override {
        Json::Value status;
        status["type"] = "Camera";
        status["recording"] = recording;
        status["resolution"] = resolution;
        status["frame_rate"] = frameRate;
        return Json::FastWriter().write(status);
    }
private:
    cv::VideoCapture cap;
    std::string resolution;
    int frameRate;
    bool recording = false;
    std::thread recordingThread;
    void initCamera() {
        cap.open(0); // 打开默认摄像头
        if (!cap.isOpened()) {
            throw std::runtime_error("Failed to open camera");
        }
        setResolution(1920, 1080);
    }
    void setResolution(int width, int height) {
        cap.set(cv::CAP_PROP_FRAME_WIDTH, width);
        cap.set(cv::CAP_PROP_FRAME_HEIGHT, height);
        resolution = std::to_string(width) + "x" + std::to_string(height);
    }
    void startRecordingThread() {
        recordingThread = std::thread([this] {
            cv::Mat frame;
            while (recording) {
                cap >> frame;
                if (frame.empty()) break;
                
                // 实现视频存储逻辑
                storeVideoFrame(frame);
                
                std::this_thread::sleep_for(
                    std::chrono::milliseconds(1000/frameRate));
            }
        });
    }
    void storeVideoFrame(const cv::Mat& frame) {
        // 实现视频帧存储逻辑
        // 示例：将帧存入内存缓冲区
        static std::vector<cv::Mat> frameBuffer;
        frameBuffer.push_back(frame.clone());
        
        if (frameBuffer.size() > 300) { // 10秒缓存（30fps）
            // 异步写入磁盘
            ThreadPool::getInstance().enqueue([buffer = std::move(frameBuffer)] {
                saveVideoToDisk(buffer);
            });
            frameBuffer.clear();
        }
    }
};